<script setup lang="ts">
defineOptions({
  name: "sopUpload"
});

import { ref, reactive, onMounted, computed } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { PxMessage } from "px-ui";
import { createSop, updateSop, querySopDetail } from "@/api/modules/operation";
import { queryEquipSystem } from "@/api/equip/archive";
import importFiles from "@/views/common/components/importFiles/index.vue";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type?: "add" | "edit";
  id?: string;
}

const props = withDefaults(defineProps<Props>(), { type: "add" });

const title = computed(() => `${props.type === "add" ? "上传" : "编辑"}CheckList`);

const dialogVisible = defineModel({ type: Boolean, default: false });

interface RuleForm {
  fileName: string;
  gasNameList: Array<string>;
  remark: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  fileName: "",
  gasNameList: [],
  remark: ""
});

const rules = reactive<FormRules<RuleForm>>({
  fileName: [{ required: true, message: "请输入SOP名称", trigger: "blur" }],
  gasNameList: [{ required: true, message: "请输入关联气体", trigger: "blur" }],
  remark: [{ required: false, message: "请输入备注", trigger: "blur" }]
});

const importFile = ref<any>({});
const gasNameOptions = ref<Array<any>>([]);
const loading = ref<boolean>(false);

const emits = defineEmits(["submit"]);

const cancelHandler = () => {
  dialogVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  const { file = "" } = importFile.value;
  if (!file && props.type === "add") {
    PxMessage.error("请上传 CheckList ！");
    return;
  }
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      if (props.type === "add") {
        let fileFormData = new FormData();
        for (const key in ruleForm) {
          fileFormData.append(key, ruleForm[key]);
        }
        // const { file = "" } = importFile.value;
        file && fileFormData.append("file", file);
        // 任务类型(1:气瓶 2：酸桶)
        const taskType = "1";
        fileFormData.append("taskType", taskType);
        await createSop(fileFormData, () => {
          loading.value = false;
        });
      } else if (props.type === "edit") {
        const { id } = props;
        const params = { ...ruleForm, id };
        await updateSop(params, () => {
          loading.value = false;
        });
      }
      loading.value = false;
      emits("submit");
      dialogVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const init = async () => {
  gasNameOptions.value = [];
  if (props.type === "edit") {
    const { id } = props;
    loading.value = true;
    const res = await querySopDetail(id, () => {
      loading.value = false;
    });
    loading.value = false;
    const { fileName = "", gasNameList = "", remark = "" } = res;
    ruleForm.fileName = fileName;
    ruleForm.gasNameList = gasNameList;
    ruleForm.remark = remark;
    // gasNameOptions.value = gasNameList.map(item => ({ label: item, value: item }));
  }
  const res: Array<any> = await queryEquipSystem({ className: "GAS" });
  // facCode   一期  FAC_83abf9   二期  FAC_93abf6
  const facCode = localStorage.getItem("facCode");
  const systemCode = facCode === "FAC_83abf9" ? "SCA6CC96" : facCode === "FAC_93abf6" ? "SCC3F1B9" : "";
  const t = res.find(item => item.code === systemCode);
  if (!t?.children?.length) return;
  gasNameOptions.value = t.children
    .map(item => {
      let { name } = item;
      const reg = new RegExp("供应系统", "g");
      name = name.replace(reg, "");
      return { label: name, value: name };
    })
    ?.filter(item => !item.label.includes("辅助系统") && !item.label.includes("电力系统") && !item.label.includes("Gas-Hookup"));
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogVisible" :title="title" :width="600">
    <div v-loading="loading" class="import-bottle">
      <div v-if="type === 'add'" class="import-bottle-title">
        上传前请先
        <span class="download"> 下载模板 </span>
        ，填写完成后导入数据
      </div>
      <div v-if="type === 'add'" class="import-bottle-upload">
        <importFiles v-model="importFile" isNotImmediateUpload />
      </div>
      <px-form ref="ruleFormRef" :model="ruleForm" :rules="rules" inline label-width="120px" class="demo-ruleForm" status-icon>
        <px-row :gutter="32">
          <px-col :span="24">
            <px-form-item label="CheckList名称" prop="fileName">
              <px-input v-model.trim="ruleForm.fileName" clearable placeholder="请输入CheckList名称" />
            </px-form-item>
          </px-col>
          <px-col :span="24">
            <px-form-item label="关联气体" prop="gasNameList">
              <px-select
                v-model="ruleForm.gasNameList"
                clearable
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                placeholder="请选择关联气体"
              >
                <px-option v-for="item in gasNameOptions" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="24">
            <px-form-item label="备注" prop="remark">
              <px-input v-model.trim="ruleForm.remark" clearable type="textarea" maxlength="200" show-word-limit placeholder="请输入备注" />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
.import-bottle {
  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin-bottom: 24px;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      color: #3b82f6;
    }
  }

  .import-bottle-upload {
    width: 100%;
    margin-bottom: 24px;
  }
}

:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
